<template>
    <view>
        <!-- 自定义导航栏 -->
        <myNavigation ref="navBar"></myNavigation>
        <view class="load_opus_container">
            <view class="opus_images_box">
                <scroll-view :scroll-x="true" enable-flex style="flex-direction: row;" class="opus_images">
                    <view class="opus_image_add" @tap.stop="uploadPhoto">+</view>
                    <block v-for="(item,index) in imagesArr" :key="index">
                        <view class="opus_image_item">
                            <image :src="item" mode="aspectFit" />
                            <view class="icon iconfont" style="display: none;">&#xe753;</view>
                        </view>
                    </block>

                </scroll-view>

                <view class="opus_des">
                    <view>作品描述：</view>
                    <textarea class="desArea" :auto-height="true" placeholder="记录美食的点滴" @input="getDes"></textarea>
                </view>
                <view class="opus_tag">
                    <view class="title">添加标签</view>
                    <textarea class="tagArea" :auto-height="true" @input="getTagStr"
                        placeholder="使用一个标签使用双#号包围,可以输入多个标签哦" />
                </view>

            </view>

        </view>
        <view class="uploadOpus_box" @tap="uploadOpus">
            <view class="uploadOpus">发&emsp;布</view>
        </view>
    </view>
</template>

<script setup>
    import { ref, onMounted, inject, reactive } from 'vue';
    import "./uploadOpus.scss";
    import Taro, { useRouter, useDidShow } from "@tarojs/taro";
    import myNavigation from "../../../components/myNavigation.vue";
    // 注入配置
    const config = inject('config');
    const baseUrl = config.baseUrl; // 从全局配置中读取 baseUrl


    // 导航栏信息
    const navBar = ref(null);
    const navigationHome = () => {
        Taro.switchTab({
            url: '../../../pages/index/index',
        });
    };
    const setNavBar = () => {
        if (navBar.value) {
            navBar.value.navigationHome = navigationHome;
            navBar.value.navigationTitle = `上传作品`;
        }
    }

    //存放图片
    const imagesArr = ref([]);

    // 上传图片
    const uploadPhoto = async () => {
        try {
            const res = await Taro.chooseImage({
                count: 1,
                sizeType: ['original', 'compressed'],
                sourceType: ['album', 'camera'],
            });

            // 返回选定照片的本地文件路径列表 tempFilePaths
            const tempFilePaths = res.tempFilePaths;
            showLoading("上传中");
            const uploadRes = await Taro.uploadFile({
                url: 'https://www.helloimg.com/api/v1/upload',
                filePath: tempFilePaths[0],
                name: 'file',
                formData: {
                    'album_id': 982,
                },

                header: {
                    'Content-Type': 'multipart/form-data',
                    'Accept': 'application/json',
                    'Authorization': 'Bearer 552|NZWxIBAYUIFtppMZOt1geLgbNUuTzXZ7yvyNKwg5',
                },
            });

            const imgData = JSON.parse(uploadRes.data);
            imagesArr.value.push(imgData.data.links.url);
        } catch (error) {
            console.error("Error uploading photo", error);
        } finally {
            // 隐藏加载中提示
            hideLoading();
        }
    };

    //作品描述
    const des = ref();
    const getDes = (e) => {
        des.value = e.detail.value
    }


    // 处理作品标签：
    const tags = ref([])
    const tagStr = ref()
    const getTagStr = (e) => {
        tagStr.value = e.detail.value
    }

    function getTag(tagStr) {
        // 使用正则表达式匹配两个 # 号之间的内容
        const pattern = /#([^#]+)#/g;
        let tags = [];
        let tag;
        // 使用正则表达式的 exec 
        while ((tag = pattern.exec(tagStr)) !== null) {
            tags.push(tag[1]); // match[1] 是捕获组的内容
        }

        return tags;
    }





    // 显示加载中提示
    function showLoading(title) {
        Taro.showLoading({
            title: `${title}`,
            mask: true,
        })
    };
    // 隐藏加载中提示
    function hideLoading() {
        Taro.hideLoading();
    };
    // 函数：上传成功后返回上一页：
    function showSuccess(msg) {
        const curTime = ref(2);
        Taro.showToast({
            title: `${msg}`,
            icon: 'success',
            mask: true,
            duration: 1000,
            complete: () => {
                const intervalId = setInterval(() => {
                    curTime.value -= 1;
                    if (curTime.value > 0) {
                        Taro.showToast({
                            title: `${msg},${curTime.value}s后返回上一页`,
                            icon: 'none',
                            mask: true,
                            duration: 1000 // 每次显示1秒
                        });
                    } else {
                        clearInterval(intervalId); // 清除定时器
                        // 执行跳转操作
                        Taro.navigateBack({
                            delta: 1
                        });
                    }
                }, 1000);
            }
        });
    }
    // 函数:失败显示
    function showError(msg) {
        Taro.showToast({
            title: `${msg}`,
            icon: 'error',
            duration: 2000, // 持续时间为2s
        });
    }




    // 存放作品信息
    const opusInfo = ref({
        userId: '',
        recipeId: '',
        images: "",
        description: "",
        tags: ""
    })

    // 发布作品
    const uploadOpus = () => {
        if (imagesArr.value.length === 0) {
            Taro.showToast({
                title: `至少上传一张图片`,
                icon: 'error',
                mask: true,
                duration: 2000
            });
            return
        };
        tags.value = getTag(tagStr.value);
        opusInfo.value.userId = curUserId.value;
        opusInfo.value.recipeId = recipeId;
        opusInfo.value.description = des.value ? des.value : "分享图片";
        opusInfo.value.tags = JSON.stringify(tags.value);
        opusInfo.value.images = JSON.stringify(imagesArr.value);
        Taro.request({
            url: `${baseUrl}/opus/uploadOpus`,
            method: 'POST',
            data: opusInfo.value,
            success: function (res) {
                if (res.data.message === "success") {
                    showSuccess(res.data.data);
                } else {
                    showError(res.data.data)
                }
            }
        });
    };


    // 存放当前登录用户id
    const curUserId = ref('');
    Taro.useDidShow(() => {
        curUserId.value = Taro.getStorageSync('userId')
    })


    //获取菜谱id，如果是用户自己发布作品，则菜谱id为-1;
    const router = useRouter();
    const { recipeId } = router.params;
    onMounted(() => {
        setNavBar();
    });
</script>

<style>

</style>